package com.vteba.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.util.List;

import com.vteba.lang.bytecode.ConstructorAccess;
import com.vteba.utils.reflection.AsmUtils;
import com.vteba.utils.serialize.Protos;

/**
 * 基于Protostuff的解码器，配合{@link LengthFieldBasedFrameDecoder}
 * @author yinlei
 * @see
 * @since 2014年11月17日 上午11:14:53
 */
public class ProtosDecoder extends ByteToMessageDecoder {
	private final ConstructorAccess<?> constructor;
	
	public ProtosDecoder(Class<?> clazz) {
		constructor = AsmUtils.createConstructorAccess(clazz);
	}
	
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in,
			List<Object> out) throws Exception {
		Object t = constructor.newInstance();
		
		byte[] bytes = new byte[in.readableBytes()];
		in.readBytes(bytes);
		Protos.mergeFrom(bytes, t);
		out.add(t);
	}

}
